class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix or not matrix[0]:
            return False
        length = len(matrix)
        n, min_n, max_n = 0, -1, len(matrix[0])
        for m in range(length):
            if matrix[m][0] > target:
                break
            n, min_n = 0, -1
            while max_n - min_n > 1:
                if matrix[m][n] == target:
                    return True
                elif matrix[m][n] > target:
                    n, max_n = (n + min_n) // 2, n
                else:
                    n, min_n = (n + max_n) // 2, n
        return False


matrix = [
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
a = Solution()
print(a.searchMatrix(matrix, 5))
print(a.searchMatrix(matrix, 20))
print(a.searchMatrix([[-5]], -5))

